package com.hkts.management.order.service.serviceimpl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hkts.management.cargo.entity.HktsCargo;
import com.hkts.management.cargo.mapper.HktsCargoMapper;
import com.hkts.management.cargo.service.IHktsCargoService;
import com.hkts.management.cargoapply.entity.HktsCargoApply;
import com.hkts.management.cargoapply.mapper.HktsCargoApplyMapper;
import com.hkts.management.cargoapply.service.IHktsCargoApplyService;
import com.hkts.management.cargodetail.entity.HktsCargoDetail;
import com.hkts.management.cargodetail.mapper.HktsCargoDetailMapper;
import com.hkts.management.cargolabel.service.serviceimpl.HktsCargoLabelServiceImpl;
import com.hkts.management.common.mq.*;
import com.hkts.management.common.utils.*;
import com.hkts.management.common.vo.*;
import com.hkts.management.contract.entity.HktsContract;
import com.hkts.management.contract.mapper.HktsContractMapper;
import com.hkts.management.contract.service.IHktsContractService;
import com.hkts.management.drivercomment.entity.DriverComment;
import com.hkts.management.drivercomment.mapper.DriverCommentMapper;
import com.hkts.management.es.EsSearchUtil;
import com.hkts.management.feign.FeignInterface;
import com.hkts.management.feign.FrontInterface;
import com.hkts.management.loadTime.service.IHktsLoadingTimeService;
import com.hkts.management.model.DTO.HktsCargoTo;
import com.hkts.management.model.DTO.PcOrderListDTO;
import com.hkts.management.model.PO.OrderAndContract;
import com.hkts.management.model.TO.AppointTo;
import com.hkts.management.model.TO.HontUserTo;
import com.hkts.management.model.VO.*;
import com.hkts.management.model.constants.CargoListVoConstants;
import com.hkts.management.model.enums.OrderStatusEnum;
import com.hkts.management.model.enums.OrderTypeEnum;
import com.hkts.management.model.result.OrderResultData;
import com.hkts.management.model.result.ResultAreaPlace;
import com.hkts.management.model.result.ResultData;
import com.hkts.management.order.entity.HktsOrder;
import com.hkts.management.order.mapper.HktsOrderMapper;
import com.hkts.management.order.service.IHktsOrderService;
import com.hkts.management.order.vo.*;
import com.hkts.management.orderrecord.entity.HktsOrderRecord;
import com.hkts.management.orderrecord.mapper.HktsOrderRecordMapper;
import com.hkts.management.orderrecord.service.IHktsOrderRecordService;
import com.hkts.management.returnfee.service.IHktsReturnFailService;
import com.hkts.management.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.join.query.JoinQueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.ParsedValueCount;
import org.elasticsearch.search.aggregations.metrics.ValueCountAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import static com.hkts.management.es.constants.EsCargoConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hml
 * @since 2021-04-24
 */
@Slf4j
@Service
@Transactional
public class HktsOrderServiceImpl extends ServiceImpl<HktsOrderMapper, HktsOrder> implements IHktsOrderService {


    @Autowired
    private HktsOrderMapper hktsOrderMapper;


    @Autowired
    private HktsCargoMapper cargoMapper;

    @Autowired
    private IHktsCargoService cargoService;


    @Autowired
    private IHktsContractService contractService;

    @Autowired
    private HktsOrderRecordMapper recordMapper;

    @Autowired
    private IHktsOrderRecordService iHktsOrderRecordService;

    @Autowired
    private HktsCargoDetailMapper detailMapper;

    @Autowired
    private HktsContractMapper contractMapper;

    @Autowired
    private HktsCargoLabelServiceImpl labelService;

    @Autowired
    private DriverCommentMapper driverCommentMapper;

    @Autowired
    private HktsCargoApplyMapper cargoApplyMapper;

    @Autowired
    private HktsCargoDetailMapper cargoDetailMapper;

    @Autowired
    private IHktsCargoApplyService iHktsCargoApplyService;

    @Autowired
    public IHktsReturnFailService iHktsReturnFailService;

    @Autowired
    private FeignInterface feignInterface;

    @Autowired
    private FrontInterface frontInterface;

    @Autowired
    private EsSearchUtil esSearchUtil;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private RegionConverUtil regionConverUtil;
    @Autowired
    private IHktsLoadingTimeService loadingTimeService;

    @Qualifier("esConfig")
    @Autowired
    private RestHighLevelClient esClient;


    @Override
    public IPage<HktsOrder> selectPage(Page<HktsOrder> page, HktsOrder hktsOrder) {
        QueryWrapper<HktsOrder> query = Wrappers.query();
        QueryWrapper<HktsOrder> entityWrapper = getEntityWrapper(query, hktsOrder);
        return hktsOrderMapper.selectPage(page, entityWrapper);
    }


    @Override
    public List<HktsOrder> selectList(HktsOrder hktsOrder) {
        QueryWrapper<HktsOrder> query = Wrappers.query();
        QueryWrapper<HktsOrder> entityWrapper = getEntityWrapper(query, hktsOrder);
        return hktsOrderMapper.selectList(entityWrapper);
    }

    /**
     * 公共查询条件
     *
     * @param entityWrapper
     * @return
     */
    public QueryWrapper<HktsOrder> getEntityWrapper(QueryWrapper<HktsOrder> entityWrapper, HktsOrder hktsOrder) {
        //条件拼接
        return entityWrapper;
    }




    /**
     * 通过id获取待签合同订单以及待同意的报名用户
     *
     * @param cargoId
     * @return
     */
    @Override
    public List<HktsOrder> getOrderByCargoIdOnStatus(String cargoId) {
        QueryWrapper<HktsOrder> query = Wrappers.query();
        query.lambda().eq(HktsOrder::getCargoId, cargoId)
                .and(wrapper -> wrapper.eq(HktsOrder::getOrderStatus, OrderTypeEnum.CONFIRMED).or().eq(HktsOrder::getOrderStatus, OrderTypeEnum.SIGN_CONTRACT));
        List<HktsOrder> hktsOrders = hktsOrderMapper.selectList(query);
        return hktsOrders;
    }

    @Override
    public List<HktsOrder> getOrderByDriverId(String driverId) {
        QueryWrapper<HktsOrder> query = Wrappers.query();
        query.lambda().eq(HktsOrder::getDriverId, driverId);
        List<HktsOrder> hktsOrders = hktsOrderMapper.selectList(query);
        return hktsOrders;
    }

    /**
     * 指定司机（新发布）
     *
     * @param hktsCargoTo
     * @return
     */
    @Override
    public Result saveOrderByAssign(HktsCargoTo hktsCargoTo) {

        HontUserTo hontUserTo = feignInterface.remoteUserInfo();
        // TODO 判断该司机是否认证
        Result<UserAndRealNameVo> driverInfoByUserId = frontInterface.getDriverInfoByUserId(hktsCargoTo.getDriverId());

        if(!driverInfoByUserId.getResult().getApproval().equals("1")){
            return ResultUtil.error("司机未完成认证，当前无法指派，请联系司机补充。");
        }
        // TODO 判断该司机是否有未确认的订单
        QueryWrapper<HktsOrder> query = Wrappers.query();
        query.lambda().eq(HktsOrder::getDriverId, hktsCargoTo.getDriverId())
                .and(wrapper -> wrapper.eq(HktsOrder::getShipperOrderStatus, 0).or().eq(HktsOrder::getShipperOrderStatus, 1).or().eq(HktsOrder::getShipperOrderStatus, 2));
        List<HktsOrder> hktsOrders = hktsOrderMapper.selectList(query);
        if (hktsOrders.size() > 0){
            return ResultUtil.error("该司机有未完成的订单");
        }
        // 发布货源 不显示
        hktsCargoTo.setAppoint(1);
        HktsCargo hktsCargo = cargoService.saveCargoAndLabelAndDetail(hktsCargoTo).getResult();
        //生成报名表
        HktsCargoApply apply = new HktsCargoApply();
        apply.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
        apply.setCargoId(hktsCargo.getId());
        apply.setDeposit(hktsCargoTo.getDeposit());
        apply.setDepositStatus(0);
        apply.setDriverId(hktsCargoTo.getDriverId());
        apply.setCheckStatus(3);
        apply.setLoadWeight(hktsCargoTo.getCargoTotal());
        cargoApplyMapper.insert(apply);
        //生成运单
        HktsOrder order = new HktsOrder();
        String orderId=String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId());
        order.setId(orderId);
        order.setCargoId(hktsCargo.getId());
        if (StringUtils.isNotBlank(hktsCargo.getStartTitle())){
            order.setStartAddress(hktsCargo.getStartTitle());
        }
        if (StringUtils.isNotBlank(hktsCargo.getEndTitle())){
            order.setEndAddress(hktsCargo.getEndTitle());
        }
        order.setShipperOrderStatus(OrderTypeEnum.CONFIRMED);
        order.setShipperOrderSubstate(OrderStatusEnum.DRIVER_CONFIRMED.getValue());
        order.setOrderStatus(OrderTypeEnum.CONFIRMED);
        order.setOrderSubstate(OrderStatusEnum.DRIVER_CONFIRMED.getValue());
        order.setDriverId(hktsCargoTo.getDriverId());
        order.setShipper(hontUserTo.getId());
        order.setPayTransportStatus(0);
        order.setApplyId(apply.getId());
        order.setIsReceipt(hktsCargo.getIsReceipt());
        order.setCompanyCode(hontUserTo.getCompanyId());
        order.setAppoint(1);
        hktsOrderMapper.insert(order);


        //生成初始化合同
        HktsContract contract = new HktsContract();
        contract.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
        contract.setStartArea(hktsCargo.getStartArea());
        contract.setStartAddressDetail(hktsCargo.getStartAddressDetail());
        contract.setStartLon(hktsCargo.getStartLon());
        contract.setStartLat(hktsCargo.getStartLat());
        contract.setEndArea(hktsCargo.getEndArea());
        contract.setEndAddressDetail(hktsCargo.getEndAddressDetail());
        contract.setEndLon(hktsCargo.getEndLon());
        contract.setEndLat(hktsCargo.getEndLat());
        contract.setOrderId(order.getId());
        contract.setCargoName(hktsCargo.getCargoName());
        contract.setContractStatus(0);
        LocalDateTime loadingTime=loadingTimeService.getFirsetLoadTimeByCargoId(hktsCargo.getId()).getLoadingStartTime();
        contract.setLoadingTime(loadingTime);
        contract.setUnloadingTime(loadingTime.plusDays(1));
        contract.setCargoWeight(hktsCargo.getCargoTotal());
        contract.setTransportPrice(hktsCargo.getTransportPrice().multiply(hktsCargo.getCargoTotal()));
        contract.setCargoType(hktsCargo.getCargoType());
        contractService.save(contract);
        iHktsOrderRecordService.addOrderRecord(order.getId(),hontUserTo.getNickName(),OrderStatusEnum.DRIVER_CONFIRMED.getValue());
        // TODO 给司机发送指定消息接口
        //发送消息
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {

                String address=regionConverUtil.regionCoverStr(Integer.valueOf(contract.getStartArea()))+"-"+regionConverUtil.regionCoverStr(Integer.valueOf(contract.getEndArea()));
                Map<String, Object> params=new HashMap<>();
                params.put("name",hontUserTo.getNickName());
                params.put("address",address);
                MsgExtras msgExtras=new MsgExtras();
                msgExtras.setOrderId(orderId);
                String messageId = String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId());
                IMessage msg = new IMessage.Builder()
                        .messageId(messageId)
                        .msgCode(IMessage.DRIVER_ASSIGN)
                        .fromUserId(hontUserTo.getId())
                        .toUserId(hktsCargoTo.getDriverId())
                        .mineType(MineType.TEMPLATE.getIndex())
                        .chatType(ChatType.UNICAST.getIndex())
                        .msgType(MsgType.JUMPTO.getIndex())
                        .param(params)
                        .extras(msgExtras)
                        .build();
                Map<?,?> msgMap= BeanConvertUtils.objectToMap(msg);
                amqpTemplate.convertAndSend(FanoutRabbitConfig.FANOUTEXCHANGE, FanoutRabbitConfig.ASSIFN, msgMap);
            }
        });
        return ResultUtil.success("指定成功");
    }

    /**
     * 指定司机（已发布）
     *
     * @param appoint
     * @return
     */
    @Override
    public Result saveOrderByAssignTo(AppointTo appoint) {
        BigDecimal zero = new BigDecimal (1);
        if (appoint.getCargoWeight().compareTo(zero) == -1){
            return ResultUtil.error("请填写正确吨数！");
        }
        HontUserTo hontUserTo = feignInterface.remoteUserInfo();
        // TODO 判断该司机是否认证
        Result<UserAndRealNameVo> driverInfoByUserId = frontInterface.getDriverInfoByUserId(appoint.getDriverId());

        if(!driverInfoByUserId.getResult().getApproval().equals("2")){
            return ResultUtil.error("司机未完成认证，当前无法指派，请联系司机补充。");

        }
        // TODO 判断该司机是否有未确认的订单
        QueryWrapper<HktsOrder> query = Wrappers.query();
        query.lambda().eq(HktsOrder::getDriverId, appoint.getDriverId())
                .and(wrapper -> wrapper.eq(HktsOrder::getShipperOrderStatus, 0).or().eq(HktsOrder::getShipperOrderStatus, 1).or().eq(HktsOrder::getShipperOrderStatus, 2));
        List<HktsOrder> hktsOrders = hktsOrderMapper.selectList(query);
        if (hktsOrders.size() > 0){
            return ResultUtil.error("该司机有未完成的订单");
        }

        //货源信息
        HktsCargo hktsCargo = cargoMapper.selectById(appoint.getCargoId());
        if (appoint.getCargoWeight().compareTo(hktsCargo.getCargoResidual()) == 1){
            return ResultUtil.error("指定吨数超过剩余吨数，请重新输入！");
        }
        HktsCargoApply apply = new HktsCargoApply();
        apply.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
        apply.setCargoId(appoint.getCargoId());
        apply.setDeposit(appoint.getDeposit());
        apply.setDepositStatus(0);
        apply.setDriverId(appoint.getDriverId());
        apply.setCheckStatus(3);
        apply.setLoadWeight(appoint.getCargoWeight());
        cargoApplyMapper.insert(apply);
        HktsOrder order = new HktsOrder();
        order.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
        order.setCargoId(appoint.getCargoId());
        if (StringUtils.isNotBlank(hktsCargo.getStartTitle())){
            order.setStartAddress(hktsCargo.getStartTitle());
        }
        if (StringUtils.isNotBlank(hktsCargo.getEndTitle())){
            order.setEndAddress(hktsCargo.getEndTitle());
        }
        order.setShipperOrderStatus(OrderTypeEnum.CONFIRMED);
        order.setShipperOrderSubstate(OrderStatusEnum.DRIVER_CONFIRMED.getValue());
        order.setOrderStatus(OrderTypeEnum.CONFIRMED);
        order.setOrderSubstate(OrderStatusEnum.DRIVER_CONFIRMED.getValue());
        order.setDriverId(appoint.getDriverId());
        order.setShipper(hontUserTo.getId());
        order.setPayTransportStatus(0);
        order.setApplyId(apply.getId());
        order.setIsReceipt(hktsCargo.getIsReceipt());
        order.setCompanyCode(hontUserTo.getCompanyId());
        order.setAppoint(1);
        hktsOrderMapper.insert(order);


        //生成初始化合同
        HktsContract contract = new HktsContract();
        contract.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
        contract.setStartArea(hktsCargo.getStartArea());
        contract.setStartAddressDetail(hktsCargo.getStartAddressDetail());
        contract.setStartLon(hktsCargo.getStartLon());
        contract.setStartLat(hktsCargo.getStartLat());
        contract.setEndArea(hktsCargo.getEndArea());
        contract.setEndAddressDetail(hktsCargo.getEndAddressDetail());
        contract.setEndLon(hktsCargo.getEndLon());
        contract.setEndLat(hktsCargo.getEndLat());
        contract.setOrderId(order.getId());
        contract.setCargoName(hktsCargo.getCargoName());
        contract.setContractStatus(0);
        LocalDateTime loadingTime=loadingTimeService.getFirsetLoadTimeByCargoId(hktsCargo.getId()).getLoadingStartTime();
        contract.setLoadingTime(loadingTime);
        contract.setUnloadingTime(loadingTime.plusDays(1));
        contract.setCargoWeight(appoint.getCargoWeight());
        contract.setTransportPrice(appoint.getTransportPrice().multiply(appoint.getCargoWeight()));
        contract.setCargoType(hktsCargo.getCargoType());
        contractService.save(contract);
        //添加订单记录
        iHktsOrderRecordService.addOrderRecord(order.getId(),hontUserTo.getNickName(),OrderStatusEnum.DRIVER_CONFIRMED.getValue());
        // TODO 给司机发送指定消息接口
        //发送消息
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {

                String address=regionConverUtil.regionCoverStr(Integer.valueOf(contract.getStartArea()))+"-"+regionConverUtil.regionCoverStr(Integer.valueOf(contract.getEndArea()));
                Map<String, Object> params=new HashMap<>();
                params.put("name",hontUserTo.getNickName());
                params.put("address",address);
                MsgExtras msgExtras=new MsgExtras();
                msgExtras.setOrderId(order.getId());
                String messageId=String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId());
                IMessage msg = new IMessage.Builder()
                        .messageId(messageId)
                        .msgCode(IMessage.DRIVER_ASSIGN)
                        .fromUserId(order.getShipper())
                        .toUserId(order.getDriverId())
                        .mineType(MineType.TEMPLATE.getIndex())
                        .chatType(ChatType.UNICAST.getIndex())
                        .msgType(MsgType.JUMPTO.getIndex())
                        .param(params)
                        .extras(msgExtras)
                        .build();
                Map<?,?> msgMap= BeanConvertUtils.objectToMap(msg);
                amqpTemplate.convertAndSend(FanoutRabbitConfig.FANOUTEXCHANGE, FanoutRabbitConfig.ASSIFN, msgMap);
            }
        });
        return ResultUtil.success("指定成功");
    }

    /**
     * 获取用户运输中与完成订单
     *
     * @param page
     * @param driverId
     * @return
     */
    @Override
    public IPage<OrderResultData> getOrderByDriverIdTo(Page page, String driverId) {

        QueryWrapper<HktsOrder> Query = Wrappers.query();
        Query.lambda().eq(HktsOrder::getDriverId, driverId).and(
                wrapper -> wrapper.eq(HktsOrder::getOrderStatus, 2).or().eq(HktsOrder::getOrderStatus, 3).or().eq(HktsOrder::getOrderStatus, 4));
        Page page1 = hktsOrderMapper.selectPage(page, Query);
        List<HktsOrder> list = page1.getRecords();

        List<OrderResultData> collect = list.stream().map(t -> assemblyOrderData(t)).collect(Collectors.toList());

        page1.setRecords(collect);
        if (collect.size() == 0){
            page1.setTotal(0);
        }
        return page1;
    }

    public OrderResultData assemblyOrderData(HktsOrder order) {

        OrderResultData resultData = new OrderResultData();
        //合同信息
        QueryWrapper<HktsContract> Query = Wrappers.query();
        Query.lambda().eq(HktsContract::getOrderId,order.getId());

        HktsContract contract = contractService.getOne(Query);
        //评论信息
        QueryWrapper<DriverComment> commentQuery = Wrappers.query();
        commentQuery.lambda().eq(DriverComment::getDriverId,order.getDriverId());

        HktsCargo hktsCargo = cargoMapper.selectById(order.getCargoId());
        String startAreaStr =  contract.getStartArea();
        String startArea = frontInterface.getRegionName(startAreaStr).getResult();
        String endAreaStr = contract.getEndArea();
        String endArea = frontInterface.getRegionName(endAreaStr).getResult();

        resultData.setStartPlace(startArea);
        resultData.setEndPlace(endArea);
        resultData.setTunnage(contract.getCargoWeight());
        resultData.setCargoName(contract.getCargoName());
        resultData.setPushTime(hktsCargo.getPushTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        if(order.getOrderStatus().getValue() == 3){
            resultData.setStatus(4);
        }else {
            resultData.setStatus(order.getOrderStatus().getValue());
        }
        return resultData;
    }

    /**
     * 运单列表
     * @param page
     * @param orderStatus
     * @return
     */
    @Override
    public IPage<PageOrderListVo> getOrdersPageByStatus(Page page, Integer orderStatus){
        HontUserTo hontUserTo = feignInterface.remoteUserInfo();
        QueryWrapper<HktsOrder> Query = Wrappers.query();
        Query.lambda().eq(HktsOrder::getShipper,hontUserTo.getId()).eq(HktsOrder::getShipperOrderStatus,orderStatus)
                .orderByDesc(HktsOrder::getCreateTime);
        Page page1 = hktsOrderMapper.selectPage(page, Query);
        List<HktsOrder> list = page1.getRecords();
        List<PageOrderListVo> result = list.stream().map(t-> resultOrderPageListByStatus(t)).collect(Collectors.toList());
        page1.setRecords(result);
        return page1;
    }
    public PageOrderListVo resultOrderPageListByStatus(HktsOrder orderPageByStatus){

        PageOrderListVo pageOrderListVo=new PageOrderListVo();
        HktsOrder order = hktsOrderMapper.selectById(orderPageByStatus.getId());

        //查询合同数据
        QueryWrapper<HktsContract> queryContract = Wrappers.query();
        queryContract.lambda().eq(HktsContract::getOrderId,orderPageByStatus.getId());
        HktsContract contract= contractMapper.selectOne(queryContract);
        //查询定金信息
        //杨春科注释 修改
      /*  QueryWrapper<HktsCargoApply> queryCargoApply = Wrappers.query();
        queryCargoApply.lambda().eq(HktsCargoApply::getCargoId,orderPageByStatus.getCargoId())
                .eq(HktsCargoApply::getDriverId,orderPageByStatus.getDriverId());*/
        HktsCargoApply cargoApply=cargoApplyMapper.selectById(orderPageByStatus.getApplyId());
        //评价信息
        QueryWrapper<DriverComment> sc = Wrappers.query();
        sc.lambda().eq(DriverComment::getOrderId,orderPageByStatus.getId());
        DriverComment driverComment = driverCommentMapper.selectOne(sc);
        pageOrderListVo.setId(orderPageByStatus.getId());
        //组装起始目的地
        String startAreaStr =  contract.getStartArea();
        String endAreaStr = contract.getEndArea();
        ResultAreaPlace startPlace=new ResultAreaPlace();
        startPlace.setAddressCode(startAreaStr);
        startPlace.setAddress(contract.getStartAddressDetail());
        Integer reginCodeStart = Integer.valueOf(contract.getStartArea());
        startPlace = regionConverUtil.regionCover(reginCodeStart, startPlace);

        startPlace.setLatitude(contract.getStartLat());
        startPlace.setLongitude(contract.getStartLon());
        startPlace.setTitle(order.getStartAddress());
        //TODO 装货时间 货源设计成时间段 合同表里取最后时间  货源表时间需重新设计
        startPlace.setDate(contract.getLoadingTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        startPlace.setTime(Integer.toString(contract.getLoadingTime().getHour()));

        ResultAreaPlace endPlace = new ResultAreaPlace();
        endPlace.setAddressCode(endAreaStr);
        endPlace.setAddress(contract.getEndAddressDetail());
        endPlace.setTitle(order.getEndAddress());
        endPlace.setLatitude(contract.getEndLat());
        endPlace.setLongitude(contract.getEndLon());
        Integer reginCodeEnd = Integer.valueOf(contract.getEndArea());
        endPlace = regionConverUtil.regionCover(reginCodeEnd, endPlace);
        if (contract.getUnloadingTime() != null){
            endPlace.setDate(contract.getUnloadingTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            endPlace.setTime(Integer.toString(contract.getUnloadingTime().getHour()));
        }
        pageOrderListVo.setStartPlace(startPlace);
        pageOrderListVo.setEndPlace(endPlace);
        //订单子状态
        pageOrderListVo.setOrderSubstate(orderPageByStatus.getShipperOrderSubstate());
        //定金信息

        if (cargoApply != null){
            ResultDataValueUnit deposit=new ResultDataValueUnit();
            deposit.setValue(cargoApply.getDeposit());
            deposit.setUnit(cargoApply.getDepositStatus());
            pageOrderListVo.setPayinfo(deposit);
        }else {
            ResultDataValueUnit deposit=new ResultDataValueUnit();
            deposit.setValue(100);
            deposit.setUnit(0);
            pageOrderListVo.setPayinfo(deposit);
        }

        //运费信息
        Map<String,Object> fregight = new HashMap<>(3);

        if (order.getPayTransportStatus() != null && order.getPayTransportStatus() == 0){
            fregight.put("transportPrice",contract.getTransportPrice());
            fregight.put("payTransportStatus",order.getPayTransportStatus());
            pageOrderListVo.setFreightinfo(fregight);
        }else {
            fregight.put("transportPrice",contract.getTransportPrice());
            fregight.put("payTransportStatus",order.getPayTransportStatus());
            fregight.put("payTransport",order.getPayTransport());
            pageOrderListVo.setFreightinfo(fregight);
        }
        if (driverComment !=null){
            Map<String,Object> evaluate = new HashMap<>(2);
            evaluate.put("value",driverComment.getScore());
            evaluate.put("content",driverComment.getContent());
            pageOrderListVo.setEvaluate(evaluate);
        }

        Map<String,Object> expressinfo = new HashMap<>(3);
        expressinfo.put("expressnum",order.getCourierCode());
        expressinfo.put("companycode",order.getCourierCompanyCode());
        expressinfo.put("company",order.getCourierCompany());
        pageOrderListVo.setExpressinfo(expressinfo);
        pageOrderListVo.setIsReceipt(order.getIsReceipt());

        Map<String,Object> goodsinfo = new HashMap<>(2);
        goodsinfo.put("name",contract.getCargoName());
        goodsinfo.put("weight",contract.getCargoWeight());
        pageOrderListVo.setGoodsinfo(goodsinfo);
        //TODO 需调取司机信息  待完善
        Result<UserAndRealNameVo> driverInfoByUserId = frontInterface.getDriverInfoByUserId(order.getDriverId());
        if(driverInfoByUserId.getResult() != null){
            if (order.getOrderStatus().getValue() == 2 || order.getOrderStatus().getValue() == 3 || order.getOrderStatus().getValue() == 4){
                UserAndRealNameVo result = driverInfoByUserId.getResult();
                result.setCarCode(contract.getCarrierPlate());
                pageOrderListVo.setDriverInfo(result);
            }else {
                pageOrderListVo.setDriverInfo(driverInfoByUserId.getResult());
            }
        }else {
            UserAndRealNameVo userAndRealNameVo = new UserAndRealNameVo();
            userAndRealNameVo.setDriverName("name");
            userAndRealNameVo.setHeadPortrait("https://i.loli.net/2019/04/28/5cc5a71a6e3b6.png");
            userAndRealNameVo.setMobile("15733210736");
            pageOrderListVo.setDriverInfo(userAndRealNameVo);

        }
        pageOrderListVo.setCarrierPlate(contract.getCarrierPlate());
        return pageOrderListVo;
    }


    /*@Override
    public List<Map<String, Object>> getOrderType() {
        HontUserTo hontUserTo = feignInterface.remoteUserInfo();
        List<Map<String, Object>> results= new ArrayList<>(7);
        OrderTypeEnum[] orderStatus= OrderTypeEnum.class.getEnumConstants();
        for (OrderTypeEnum item:orderStatus
        ) {
            int count=0;
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
            queryBuilder.filter(QueryBuilders.termQuery(TYPE,CHILD_TYPE));
            //根据司机查询
            queryBuilder.filter(QueryBuilders.termQuery(SHIPPER,hontUserTo.getId()));
            queryBuilder.filter(QueryBuilders.termQuery(SHIPPERORDERSTATUS,item.getValue()));
            searchSourceBuilder.query(queryBuilder);
            Map<String,Object>  data=esSearchUtil.search(CARGO_ORDER_INDEX,searchSourceBuilder);
            if(data==null||Integer.parseInt(data.get("count").toString())==0){
                log.error("es查询数据为空{}",data);
            }else{
                count=Integer.parseInt(String.valueOf(data.get("total")));
            }
            Map<String,Object> result=new HashMap<>(3);
            result.put("orderType",item.getValue());
            result.put("orderTypeDesc",item.getDesc());
            result.put("count",count);
            results.add(result);
        }
        log.info("获取订单状态{}",results);
        return results;
    }*/
    @Override
    public List<Map<String, Object>> getOrderType() {
        // 根据货主id获取数据
        HontUserTo hontUserTo = feignInterface.remoteUserInfo();
        List<Map<String,Object>> counts=hktsOrderMapper.selectCountAndStatus(hontUserTo.getId());
        List<Map<String, Object>> results= new ArrayList<>(7);
        OrderTypeEnum[] orderStatus= OrderTypeEnum.class.getEnumConstants();
//        OrderTypeEnum[] orderStatus= OrderStatusEnum.values();
        for (OrderTypeEnum item:orderStatus
        ) {
            Map<String,Object> result=new HashMap<>(3);
            result.put("orderType",item.getValue());
            result.put("orderTypeDesc",item.getDesc());
            int count=0;
            if(counts.size()>0){
                for (Map<String,Object> map:counts
                ) {
                    if(map.get("orderStatus")==item.getValue()){
                        count= Integer.parseInt(map.get("count").toString());
                    }
                }
            }
            result.put("count",count);
            results.add(result);
        }
        log.info("获取订单状态{}",results);
        return results;
    }

    @Override
    public List<Map<String, Object>>  getOrderSubStatus() {
        OrderStatusEnum[] orderStatus= OrderStatusEnum.class.getEnumConstants();
        List<Map<String, Object>> results= new ArrayList<>(11);
        Map<String,Object> all=new HashMap<>(3);
        all.put("orderSubState",-1);
        all.put("orderSubStateDesc","全部");
        results.add(all);
        for (OrderStatusEnum item:orderStatus
        ) {
            Map<String,Object> result=new HashMap<>(3);

            switch (item){
                case CONFIRMED:
                    result.put("orderSubState",111);
                    result.put("orderSubStateDesc",OrderStatusEnum.CONFIRMED.getDesc());
                    results.add(result);
                    break;
                case REFUSE_CANCEL:
                    result.put("orderSubState",8910);
                    result.put("orderSubStateDesc","已取消");
                    results.add(result);
                    break;
                case DRIVER_CANCEL:
                case OWNER_CANCEL:
                case DRIVER_CONFIRMED:
                    break;
                default:
                    result.put("orderSubState",item.getValue());
                    result.put("orderSubStateDesc",item.getDesc());
                    results.add(result);
                    break;
            }

        }
        return results;
    }

    @Override
    public Map<String,Object> getCargoDetailByOrderId(String orderId){
        HktsOrder order = hktsOrderMapper.selectById(orderId);
        //货物
        HktsCargo hktsCargo = cargoMapper.selectById(order.getCargoId());
        QueryWrapper<HktsCargoDetail> query = Wrappers.query();
        query.lambda().eq(HktsCargoDetail::getCargoId, hktsCargo.getId());
        HktsCargoDetail hktsCargoDetail = cargoDetailMapper.selectOne(query);
        Map<String,Object> result = new HashMap<>();
        List<Object> carType=new ArrayList<>();
        carType.add(StringUtil.spilt(StringUtils.strip(labelService.getCargoLanelByCargoId(hktsCargo.getId(), 4).toString(),"[]").replace(" ", "")));
        carType.add(StringUtils.strip(labelService.getCargoLanelByCargoId(hktsCargo.getId(), 3).toString(),"[]").replace(" ", ""));
        List<Object> lodingType=new ArrayList<>();
        lodingType.add(StringUtils.strip(labelService.getCargoLanelByCargoId(hktsCargo.getId(), 0).toString(),"[]").replace(" ", ""));
        lodingType.add(StringUtils.strip(labelService.getCargoLanelByCargoId(hktsCargo.getId(), 1).toString(),"[]").replace(" ", ""));
        lodingType.add(hktsCargo.getCargoTotal() + hktsCargo.getCargoUnit());
        result.put(CargoListVoConstants.CARTYPE,carType);
        result.put(CargoListVoConstants.CARGOTYPE,lodingType);
        result.put(CargoListVoConstants.LOADINGMODE,StringUtils.strip(labelService.getCargoLanelByCargoId(hktsCargo.getId(), 2).toString(),"[]").replace(" ", ""));
        result.put("remark",hktsCargoDetail.getRemark());
        return result;
    }
    /**
     * 运单详情
     * @param orderId
     * @param driverId
     */
    @Override
    public ResultData getOrderDetailById(String orderId,String driverId){
        //订单
        HktsOrder order = hktsOrderMapper.selectById(orderId);
        //货物
        HktsCargo hktsCargo = cargoMapper.selectById(order.getCargoId());
        QueryWrapper<HktsContract> Query = Wrappers.query();
        //合同
        Query.lambda().eq(HktsContract::getOrderId,orderId);
        HktsContract contract = contractService.getOne(Query);

        ResultData resultData = assemblyCargoData(hktsCargo, contract, order);
        //合同

        return resultData;
    }
    private ResultData assemblyCargoData(HktsCargo hktsCargo,HktsContract contract,HktsOrder order){

        ResultData hktsCargoVo = new ResultData();
        //查询运输信息
        QueryWrapper<HktsCargoDetail> queryCargoDetail = Wrappers.query();
        queryCargoDetail.lambda().eq(HktsCargoDetail::getCargoId,hktsCargo.getId());
        HktsCargoDetail cargoDetail = detailMapper.selectOne(queryCargoDetail);
        //起始地
        hktsCargoVo=assemblyAreaPlace(hktsCargoVo,contract);
        //货物信息
        Map<String ,Object> totalinfo=new HashMap<>();

        List<Object> list=new ArrayList<>();
        Map<String ,Object> godInfo=new HashMap<>();
        godInfo.put(CargoListVoConstants.CARGOTYPE,StringUtils.strip(labelService.getCargoLanelByCargoId(hktsCargo.getId(), 0).toString(),"[]").replace(" ", ""));
        godInfo.put(CargoListVoConstants.PACKMODE,StringUtils.strip(labelService.getCargoLanelByCargoId(hktsCargo.getId(), 1).toString(),"[]").replace(" ", ""));
        godInfo.put(CargoListVoConstants.CARGOtOTAL,hktsCargo.getCargoTotal());
        list.add(godInfo);

        totalinfo.put("cargoWeight",contract.getCargoWeight());
        totalinfo.put(CargoListVoConstants.CARGORESIDUALUNIT,hktsCargo.getCargoUnit());

        //其他信息
        totalinfo.put("orderTime",order.getCreateTime());
        //定金信息
        //杨春科改 将司机货源修改为根据报名id
        QueryWrapper<HktsCargoApply> queryCargoApply = Wrappers.query();
        queryCargoApply.lambda().eq(HktsCargoApply::getId,order.getApplyId());
        HktsCargoApply cargoApply = cargoApplyMapper.selectOne(queryCargoApply);
        if (cargoApply != null){
            totalinfo.put("deposit",cargoApply.getDeposit());
            totalinfo.put("depositStatus",cargoApply.getDepositStatus());
            totalinfo.put("payOrder",cargoApply.getPayOrder());
        }else {
            totalinfo.put("deposit",100);
            totalinfo.put("depositStatus",0);
            totalinfo.put("payOrder","");
        }
        //运输信息
        totalinfo.put("estimateDistance",cargoDetail.getEstimateDistance());
        //运费信息
        totalinfo.put("univalence",contract.getTransportPrice().divide(contract.getCargoWeight(),2, BigDecimal.ROUND_HALF_UP));
        totalinfo.put(CargoListVoConstants.TRANSPORTPRICE,contract.getTransportPrice());
        totalinfo.put("payTransportStatus",order.getPayTransportStatus());
        totalinfo.put("payTransport",order.getPayTransport());
        totalinfo.put("subStatus",order.getShipperOrderSubstate());
        totalinfo.put("orderStatus",order.getShipperOrderStatus().getValue());
        //快递回单
        totalinfo.put("expressnum",order.getCourierCode());
        totalinfo.put("company",order.getCourierCompany());
        totalinfo.put("companycode",order.getCourierCompanyCode());
        totalinfo.put("carrierPlate",contract.getCarrierPlate());
        totalinfo.put("actualPayTime",order.getActualPayTime());
        hktsCargoVo.setTotalinfo(totalinfo);
        hktsCargoVo.setGoodsInfos(list);
        hktsCargoVo.setId(order.getId());
        //TODO 司机信息
        Result<UserAndRealNameVo> driverInfoByUserId = frontInterface.getDriverInfoByUserId(order.getDriverId());
        if (order.getOrderStatus().getValue() == 2 || order.getOrderStatus().getValue() == 3 || order.getOrderStatus().getValue() == 4){
            UserAndRealNameVo result = driverInfoByUserId.getResult();
            result.setCarCode(contract.getCarrierPlate());
            hktsCargoVo.setDriverInfo(result);
        }else {
            hktsCargoVo.setDriverInfo(driverInfoByUserId.getResult());
        }
        return hktsCargoVo;
    }
    public ResultData assemblyAreaPlace( ResultData resultData,HktsContract contract){
        //组装起始地
        //组装起始目的地
        HktsOrder hktsOrder = hktsOrderMapper.selectById(contract.getOrderId());
        String startAreaStr =  contract.getStartArea();
        String endAreaStr = contract.getEndArea();
        ResultAreaPlace startPlace=new ResultAreaPlace();
        startPlace.setAddressCode(startAreaStr);
        startPlace.setAddress(contract.getStartAddressDetail());
        startPlace.setTitle(hktsOrder.getStartAddress());
        Integer reginCodeStart = Integer.valueOf(contract.getStartArea());
        startPlace = regionConverUtil.regionCover(reginCodeStart, startPlace);
        startPlace.setLatitude(contract.getStartLat());
        startPlace.setLongitude(contract.getStartLon());

        //TODO 装货时间 货源设计成时间段 合同表里取最后时间  货源表时间需重新设计
        startPlace.setDate(contract.getLoadingTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        startPlace.setTime(Integer.toString(contract.getLoadingTime().getHour()));

        ResultAreaPlace endPlace = new ResultAreaPlace();
        endPlace.setAddressCode(endAreaStr);
        endPlace.setAddress(contract.getEndAddressDetail());
        endPlace.setLatitude(contract.getEndLat());
        endPlace.setLongitude(contract.getEndLon());
        endPlace.setTitle(hktsOrder.getEndAddress());
        Integer reginCodeEnd = Integer.valueOf(contract.getEndArea());
        endPlace = regionConverUtil.regionCover(reginCodeEnd, endPlace);
        if (contract.getUnloadingTime() != null){
            endPlace.setDate(contract.getUnloadingTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            endPlace.setTime(Integer.toString(contract.getUnloadingTime().getHour()));
        }
        resultData.setStartPlace(startPlace);
        resultData.setEndPlace(endPlace);
        return resultData;
    }

    /**
     *
     * @param orderId
     */
    @Override
    public void confirmReceipt(String orderId){
        HontUserTo hontUserTo = feignInterface.remoteUserInfo();
        hktsOrderMapper.updateOnShipperByOrderId(orderId,OrderTypeEnum.EVALUATE,OrderStatusEnum.EVALUATE.getValue(),hontUserTo.getNickName(),LocalDateTime.now());
        HktsOrder order = hktsOrderMapper.selectById(orderId);
        QueryWrapper<HktsCargoApply> applyQuery = Wrappers.query();
        applyQuery.lambda().eq(HktsCargoApply::getCargoId,order.getCargoId())
                .eq(HktsCargoApply::getDriverId,order.getDriverId()).eq(HktsCargoApply::getCheckStatus,0);
        //TODO es同步数据
        updateOrderOnEs(order.getId(),order.getOrderStatus(),order.getOrderSubstate());

        iHktsOrderRecordService.addOrderRecord(order.getId(),hontUserTo.getNickName(),OrderStatusEnum.EVALUATE.getValue());
    }

    @Override
    public Result<Object> cancelOrder(String orderId){
        HontUserTo hontUserTo = feignInterface.remoteUserInfo();
        if(hontUserTo==null){
            return ResultUtil.error(401,"获取当前登录异常");
        }
        //合同失效
        QueryWrapper<HktsContract> query = Wrappers.query();
        query.lambda().eq(HktsContract::getOrderId,orderId);
        HktsContract contract = contractService.getOne(query);
        contractMapper.updateContractByOrderId(orderId);
        //报名拒绝
        HktsOrder order = hktsOrderMapper.selectById(orderId);
        /*QueryWrapper<HktsCargoApply> applyQuery = Wrappers.query();
        applyQuery.lambda().eq(HktsCargoApply::getCargoId,order.getCargoId())
                .eq(HktsCargoApply::getDriverId,order.getDriverId());*/
        hktsOrderMapper.updateByOrderId(orderId,OrderTypeEnum.CANCEL,OrderStatusEnum.OWNER_CANCEL.getValue(),LocalDateTime.now());
        HktsCargo hktsCargo = cargoMapper.selectById(order.getCargoId());
        if (hktsCargo.getAppoint() == 1){
            hktsCargo.setCargoStatus(1);
            cargoMapper.updateCargoById(hktsCargo);
        }

        iHktsOrderRecordService.addOrderRecord(order.getId(),hontUserTo.getNickName(),OrderStatusEnum.OWNER_CANCEL.getValue());
        /**
         * 报名表
         */
        // TODO 退款
        String format = "YYYY-MM-dd hh:mm:ss";
        HktsCargoApply hktsCargoApply = cargoApplyMapper.selectById(order.getApplyId());

        if(hktsCargoApply.getDepositStatus() == PayConstants.PAID){

            cargoApplyMapper.updateByCargoId(hktsCargoApply.getId(),hontUserTo.getNickName(),PayConstants.AUDIT_FAILED,PayConstants.AUDIT_FAILED,LocalDateTime.now().format(DateTimeFormatter.ofPattern(format)));
            iHktsReturnFailService.returnFee(hktsCargoApply);
        }else {
            cargoApplyMapper.updateByCargoId(hktsCargoApply.getId(),hontUserTo.getNickName(),PayConstants.AUDIT_FAILED,hktsCargoApply.getDepositStatus(),LocalDateTime.now().format(DateTimeFormatter.ofPattern(format)));
        }
        //TODO es同步数据
        updateOrderOnEs(order.getId(),OrderTypeEnum.CANCEL,OrderStatusEnum.OWNER_CANCEL.getValue());
        //发送消息
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {

                String address=regionConverUtil.regionCoverStr(Integer.valueOf(contract.getStartArea()))+"-"+regionConverUtil.regionCoverStr(Integer.valueOf(contract.getEndArea()));
                Map<String, Object> params=new HashMap<>();
                params.put("time", contract.getLoadingTime().toLocalDate());
                params.put("address",address);
                MsgExtras msgExtras=new MsgExtras();
                msgExtras.setOrderId(order.getId());
                String messageId=String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId());
                IMessage msg = new IMessage.Builder()
                        .messageId(messageId)
                        .msgCode(IMessage.CANCEL)
                        .fromUserId(order.getShipper())
                        .toUserId(order.getDriverId())
                        .mineType(MineType.TEMPLATE.getIndex())
                        .chatType(ChatType.UNICAST.getIndex())
                        .msgType(MsgType.JUMPTO.getIndex())
                        .param(params)
                        .extras(msgExtras)
                        .build();
                Map<?,?> msgMap= BeanConvertUtils.objectToMap(msg);
                amqpTemplate.convertAndSend(FanoutRabbitConfig.FANOUTEXCHANGE, FanoutRabbitConfig.ASSIFN, msgMap);
            }
        });
        return ResultUtil.success("取消成功");
    }
    @Override
    public Result<Object> cancelOrderPc(String orderId,Integer isRefund,String refundDescribe){
        HontUserTo hontUserTo = feignInterface.remoteUserInfo();
        if(hontUserTo==null){
            return ResultUtil.error(401,"获取当前登录异常");
        }
        //合同失效
        QueryWrapper<HktsContract> query = Wrappers.query();
        query.lambda().eq(HktsContract::getOrderId,orderId);
        HktsContract contract = contractService.getOne(query);
        contractMapper.updateContractByOrderId(orderId);
        //报名拒绝
        HktsOrder order = hktsOrderMapper.selectById(orderId);
        /*QueryWrapper<HktsCargoApply> applyQuery = Wrappers.query();
        applyQuery.lambda().eq(HktsCargoApply::getCargoId,order.getCargoId())
                .eq(HktsCargoApply::getDriverId,order.getDriverId());*/
        CancelOrderInfoParameterVo cancelOrderInfoParameterVo = new CancelOrderInfoParameterVo();
        cancelOrderInfoParameterVo.setOrderId(orderId);
        cancelOrderInfoParameterVo.setRefundDescribe(refundDescribe);
        cancelOrderInfoParameterVo.setStatus(OrderTypeEnum.CANCEL.getValue());
        cancelOrderInfoParameterVo.setSubstate(OrderStatusEnum.OWNER_CANCEL.getValue());
        cancelOrderInfoParameterVo.setTime(LocalDateTime.now());
        cancelOrderInfoParameterVo.setIsRefund(isRefund);
        hktsOrderMapper.updateCancelOrder(cancelOrderInfoParameterVo);
        HktsCargo hktsCargo = cargoMapper.selectById(order.getCargoId());
        if (hktsCargo.getAppoint() == 1){
            hktsCargo.setCargoStatus(1);
            cargoMapper.updateCargoById(hktsCargo);
        }

        iHktsOrderRecordService.addOrderRecord(order.getId(),hontUserTo.getNickName(),OrderStatusEnum.OWNER_CANCEL.getValue());
        /**
         * 报名表
         */
        // TODO 退款
        String format = "YYYY-MM-dd hh:mm:ss";
        HktsCargoApply hktsCargoApply = cargoApplyMapper.selectById(order.getApplyId());

        if(hktsCargoApply.getDepositStatus() == PayConstants.PAID && isRefund == 0){

            cargoApplyMapper.updateByCargoId(hktsCargoApply.getId(),hontUserTo.getNickName(),PayConstants.AUDIT_FAILED,PayConstants.AUDIT_FAILED,LocalDateTime.now().format(DateTimeFormatter.ofPattern(format)));
            iHktsReturnFailService.returnFee(hktsCargoApply);
        }else {
            cargoApplyMapper.updateByCargoId(hktsCargoApply.getId(),hontUserTo.getNickName(),PayConstants.AUDIT_FAILED,hktsCargoApply.getDepositStatus(),LocalDateTime.now().format(DateTimeFormatter.ofPattern(format)));
        }
        //TODO es同步数据
        updateOrderOnEs(order.getId(),OrderTypeEnum.CANCEL,OrderStatusEnum.OWNER_CANCEL.getValue());
        //发送消息
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {

                String address=regionConverUtil.regionCoverStr(Integer.valueOf(contract.getStartArea()))+"-"+regionConverUtil.regionCoverStr(Integer.valueOf(contract.getEndArea()));
                Map<String, Object> params=new HashMap<>();
                params.put("time", contract.getLoadingTime().toLocalDate());
                params.put("address",address);
                MsgExtras msgExtras=new MsgExtras();
                msgExtras.setOrderId(order.getId());
                String messageId=String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId());
                IMessage msg = new IMessage.Builder()
                        .messageId(messageId)
                        .msgCode(IMessage.CANCEL)
                        .fromUserId(order.getShipper())
                        .toUserId(order.getDriverId())
                        .mineType(MineType.TEMPLATE.getIndex())
                        .chatType(ChatType.UNICAST.getIndex())
                        .msgType(MsgType.JUMPTO.getIndex())
                        .param(params)
                        .extras(msgExtras)
                        .build();
                Map<?,?> msgMap= BeanConvertUtils.objectToMap(msg);
                amqpTemplate.convertAndSend(FanoutRabbitConfig.FANOUTEXCHANGE, FanoutRabbitConfig.ASSIFN, msgMap);
            }
        });
        return ResultUtil.success("取消成功");
    }
    @Override
    public  IPage searchOrder(Page page,String serarchInfo, String time, String status) {
        HontUserTo hontUserTo = feignInterface.remoteUserInfo();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //配置分页
        searchSourceBuilder.from(Integer.parseInt(String.valueOf((page.getCurrent()-1)*page.getSize())));
        searchSourceBuilder.size(Integer.parseInt(String.valueOf(page.getSize())));
        //配置查询参数
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.filter(QueryBuilders.termQuery(TYPE,CHILD_TYPE));
        //根据货主查询查询
        queryBuilder.filter(QueryBuilders.termQuery(SHIPPER,hontUserTo.getId()));
        if(serarchInfo!=null&&!"".equals(serarchInfo)){
            String[] files=new String[]{USERNAME,STARTAREA,TELPHONE};
            queryBuilder.filter(JoinQueryBuilders.hasParentQuery(PARENT_TYPE,QueryBuilders.multiMatchQuery(serarchInfo,files), true));
            queryBuilder.filter(JoinQueryBuilders.hasParentQuery(PARENT_TYPE,QueryBuilders.termQuery(USERID,hontUserTo.getId()), true));
        }
        if(status!=null&&!"".equals(status)){
            queryBuilder.filter(QueryBuilders.termQuery(SHIPPERORDERSTATUS,status));
        }
        if(time!=null&&!"".equals(time)){
            String[] times=time.split(",");
            if( times.length > 1 ){
                queryBuilder.filter(QueryBuilders.rangeQuery(ORDER_CREATETIME).gte(times[0]).lte(times[1]));
            }
        }
        searchSourceBuilder.query(queryBuilder);

        Map<String,Object>  data=esSearchUtil.search(CARGO_ORDER_INDEX,searchSourceBuilder);
        //TODO 未封装分页总计
        if(data==null){
            page.setRecords(null);
            return page;
        }
        if (data.get("count").toString().equals("0")){
            page.setRecords(null);
            return page;
        }
        List<Map<String,Object>> datas= JSON.parseObject(JSON.toJSONString(data.get("data")),List.class);
        List<String> ids=datas.stream().map(e->e.get("orderId").toString()).collect(Collectors.toList());
        List<PageOrderListVo> result= new ArrayList<>();
        if (ids.size() == 0){

            page.setTotal( Long.parseLong(String.valueOf(data.get("count"))));
            page.setRecords(result);
            return page;
        }
        QueryWrapper<HktsOrder> query = Wrappers.query();
        query.lambda().in(HktsOrder::getId,ids);
        List<HktsOrder> orders=hktsOrderMapper.selectList(query);

        if(orders.size()>0){
            result=orders.stream().map(this::resultOrderPageListByStatus).collect(Collectors.toList());
        }
        page.setTotal( Long.parseLong(String.valueOf(data.get("count"))));
        page.setRecords(result);
        return page;
    }

    /**
     * 修改报名状态
     * @param orderId
     * @param status
     * @return
     */
    @Override
    public Result updateApplyStatus(String orderId,Integer status){
        return iHktsCargoApplyService.updateCheckStatus(orderId,status);

    }

    /**
     * 订单同步es
     * @param id
     * @param orderType
     * @param subState
     */
    @Override
    public void updateOrderOnEs(String id,OrderTypeEnum orderType,Integer subState){
        //同步es数据
        String orderId=ORDER_PREFIX+id;
        Map<String,Object> map= esSearchUtil.getEsDateById(CARGO_ORDER_INDEX,orderId);
        if(map==null||Integer.parseInt(map.get("count").toString())==0) {
            log.error("同步订单数据，es查询数据为空{}", map);
            return;
        }
        Map<String, Object> orderEsData = new ConcurrentHashMap<>(2);
        orderEsData.put(ORDERSTATUS,orderType.getValue());
        orderEsData.put(ORDER_SUBSTATE,subState);
        orderEsData.put(SHIPPERORDERSTATUS,orderType.getValue());
        orderEsData.put(SHIPPERORDERSUBSTATE,subState);
        log.info("es同步订单数据{},订单id{}",orderEsData,orderId);
        //TODO es同步数据
        esSearchUtil.updateToEs(orderEsData,CARGO_ORDER_INDEX,orderId);
    }

    @Override
    public Result<Object> getOrderListOnPc(Page<OrderAndContract> page, PcOrderListDTO pcOrderListDTO) {
        LocalDateTime s=LocalDateTime.now();
        log.info("pc端参数{},开始时间{}",pcOrderListDTO,DateUtils.getCurrentTime());
        QueryWrapper<HktsOrder> query = Wrappers.query();
        query.lambda().eq(!(pcOrderListDTO.getCargoId()==null||"".equals(pcOrderListDTO.getCargoId())),HktsOrder::getCargoId,pcOrderListDTO.getCargoId());
        query.lambda().eq(!(pcOrderListDTO.getDriverId()==null||"".equals(pcOrderListDTO.getDriverId())),HktsOrder::getDriverId,pcOrderListDTO.getDriverId());

        if(pcOrderListDTO.getSubStatus()!=null){
            switch (pcOrderListDTO.getSubStatus()){
                case -1:
                    break;
                case 8910:
                    query.lambda().eq(HktsOrder::getShipperOrderStatus,OrderTypeEnum.CANCEL);
                    break;
                case 111:
                    query.lambda().eq(HktsOrder::getShipperOrderStatus,OrderTypeEnum.CONFIRMED);
                    break;
                default:
                    query.lambda().eq(HktsOrder::getShipperOrderSubstate,pcOrderListDTO.getSubStatus());
                    break;
            }
        }
        if(pcOrderListDTO.getSearchType()!=null){
            if(pcOrderListDTO.getSearchContent()!=null&&!"".equals(pcOrderListDTO.getSearchContent())){
                switch (pcOrderListDTO.getSearchType()){
                    case 0:
                        break;
                    case 1:
                        query.like("hkts_contract.START_ADDRESS_DETAIL",pcOrderListDTO.getSearchContent());
                        break;
                    case 2:
                        query.like("hkts_contract.END_ADDRESS_DETAIL",pcOrderListDTO.getSearchContent());
                        break;
                    case 3:
                        query.like("hkts_contract.CARGO_NAME",pcOrderListDTO.getSearchContent());
                        break;
                    case 4:
                        query.eq("hkts_order.ID",pcOrderListDTO.getSearchContent());
                        break;
                    case 5:
                        Result<List<DriverListInfoVo>> result=frontInterface.getDriverInfosByMobile(pcOrderListDTO.getSearchContent());
                        if(result.isSuccess()&&result.getResult().size()>0){
                            List<DriverListInfoVo> driverListInfoVo=result.getResult();
                            List<String> collect = driverListInfoVo.stream().map(DriverListInfoVo::getId).collect(Collectors.toList());
                            query.lambda().in(HktsOrder::getDriverId,collect);
                        } else{
                            query.lambda().in(HktsOrder::getDriverId,"");
                        }
                        break;
                    case 6:
                        Result<List<String>> listResult= frontInterface.getIdsByDriverName(pcOrderListDTO.getSearchContent());
                        if(listResult.isSuccess()&&listResult.getResult().size()>0){
                                query.lambda().in(HktsOrder::getDriverId,listResult.getResult());
                        } else{
                            query.lambda().in(HktsOrder::getDriverId,"");
                        }
                        break;
                    case 7:
                        Result<List<UserBasicInfoVo>> userBasicInfoVoResult = feignInterface.getUserByNickName(pcOrderListDTO.getSearchContent());
                        if(userBasicInfoVoResult.isSuccess()&&userBasicInfoVoResult.getResult().size()>0){
                            List<String> ids=userBasicInfoVoResult.getResult().stream().map(UserBasicInfoVo::getId).collect(Collectors.toList());
                            query.lambda().in(HktsOrder::getShipper,ids);
                        }else{
                            query.lambda().in(HktsOrder::getShipper,"");

                        }
                        break;
                }
            }
        }

//        query.eq(address!=null&&!"".equals(address),"hkts_contract.START_AREA",address);
        if(pcOrderListDTO.getStartTime()!=null&&!"".equals(pcOrderListDTO.getStartTime())){
            LocalDate localDateTime= DateConverUtils.parseStringToDate(pcOrderListDTO.getStartTime());
            query.ge("hkts_contract.LOADING_TIME",localDateTime);
        }
        if(pcOrderListDTO.getEndTime()!=null&&!"".equals(pcOrderListDTO.getEndTime())){
            LocalDate localDateTime= DateConverUtils.parseStringToDate(pcOrderListDTO.getEndTime());
            query.le("hkts_contract.LOADING_TIME",localDateTime);
        }
        query.orderByDesc("hkts_order.CREATE_TIME");
        log.info("组装参数完成{}",DateUtils.intervalMillis(s,LocalDateTime.now()));
        IPage<OrderAndContract> page1=hktsOrderMapper.selectOrderAndContract(page,query);
        log.info("查询完成{}",DateUtils.intervalMillis(s,LocalDateTime.now()));
        List<OrderAndContract> orderAndContracts=page1.getRecords();
        CustomPage customPage= CustomPageUtils.getCustomPage(page1);
        if(orderAndContracts!=null&&orderAndContracts.size()>0){
            List<String> userIds = new ArrayList<>();
            List<String> driverIds = new ArrayList<>();
            for (OrderAndContract item:orderAndContracts
                 ) {
                userIds.add(item.getShipper());
                driverIds.add(item.getDriverId());
            }
            Result<Map<String, Object>> user= feignInterface.getUsersByuserIds(userIds);
            Result<Map<String,Object>>   driver=frontInterface.getDriverInfosByUserIds(driverIds);
            List<HktsOrderOnPCVo> hktsOrderOnPCVos= orderAndContracts.stream().map(t->getHktsOrderOnPCVo(t,user,driver)).collect(Collectors.toList());
            customPage.setResultData(hktsOrderOnPCVos);
        }
        log.info("方法时间差{}",DateUtils.intervalMillis(s,LocalDateTime.now()));
        return ResultUtil.data(customPage);
    }
    public HktsOrderOnPCVo getHktsOrderOnPCVo(OrderAndContract hktsOrder,Result<Map<String, Object>> users,Result<Map<String, Object>> drivers){
        LocalDateTime s=LocalDateTime.now();
        log.info("组装开始时间{}",LocalDateTime.now());
        HktsOrderOnPCVo orderOnPCVo=new HktsOrderOnPCVo();
        orderOnPCVo.setId(hktsOrder.getId());
        orderOnPCVo.setCargoId(hktsOrder.getCargoId());
        orderOnPCVo.setDriverId(hktsOrder.getDriverId());
        orderOnPCVo.setShipper(hktsOrder.getShipper());
        orderOnPCVo.setShipperOrderStatus(hktsOrder.getShipperOrderStatus());
        orderOnPCVo.setShipperOrderSubstate(hktsOrder.getShipperOrderSubstate());
        orderOnPCVo.setApplyId(hktsOrder.getApplyId());
        orderOnPCVo.setCreateTime(hktsOrder.getCreateTime());
        log.info("基本数据完成{}",DateUtils.intervalMillis(s,LocalDateTime.now()));
//        String address=regionConverUtil.regionCoverStr(Integer.valueOf(hktsOrder.getStartArea()))+"-"+regionConverUtil.regionCoverStr(Integer.valueOf(hktsOrder.getEndArea()));
        String startPlace=regionConverUtil.regionCoverMap(Integer.valueOf(hktsOrder.getStartArea())).get(RegionConstants.CITY).toString()+(hktsOrder.getStartAddress()==null?"":hktsOrder.getStartAddress());
        String endPlace=regionConverUtil.regionCoverMap(Integer.valueOf(hktsOrder.getEndArea())).get(RegionConstants.CITY).toString()+(hktsOrder.getEndAddress()==null?"":hktsOrder.getEndAddress());
        orderOnPCVo.setStartPlace(startPlace);
        orderOnPCVo.setEndPlace(endPlace);
        log.info("组装省市县完成{}",DateUtils.intervalMillis(s,LocalDateTime.now()));
//        Result<UserAndRealNameVo> userAndRealNameVoResult=frontInterface.getDriverInfoByUserId(hktsOrder.getDriverId());
//        log.info("用户id{}用户信息{}",hktsOrder.getDriverId(),userAndRealNameVoResult);
//        if(userAndRealNameVoResult.isSuccess()&&userAndRealNameVoResult.getResult()!=null){
//            UserAndRealNameVo userAndRealNameVo=userAndRealNameVoResult.getResult();
//            orderOnPCVo.setDriverName(userAndRealNameVo.getDriverName());
//            orderOnPCVo.setLicencePlate(userAndRealNameVo.getCarCode());
//            orderOnPCVo.setPhone(userAndRealNameVo.getMobile());
//        }
        if(drivers.isSuccess()&&drivers.getResult()!=null){
            Map<String, Object> driverMap=drivers.getResult();
            try {
                UserAndRealNameVo userAndRealNameVo= BeanConvertUtils.convertBean(driverMap.get(hktsOrder.getDriverId()),UserAndRealNameVo.class);
                orderOnPCVo.setDriverName(userAndRealNameVo.getDriverName());
                orderOnPCVo.setLicencePlate(userAndRealNameVo.getCarCode());
                orderOnPCVo.setPhone(userAndRealNameVo.getMobile());
            }catch (Exception e){
                log.error("订单列表司机Id{}用户数据异常",hktsOrder.getDriverId());
            }
        }
        log.info("组装用户信息完成{}",DateUtils.intervalMillis(s,LocalDateTime.now()));
//        Result<UserVo> userVoResult=feignInterface.getUserByuserId(hktsOrder.getShipper());
//        if(userVoResult.isSuccess()&&userVoResult.getResult()!=null){
//            UserVo userVo=userVoResult.getResult();
//            orderOnPCVo.setShipperName(userVo.getNickName());
//        }
//        Result<UserVo> userVoResult=feignInterface.getUserByuserId(hktsOrder.getShipper());
        if(users.isSuccess()&&users.getResult()!=null){
            Map<String, Object> userMap=users.getResult();
            try {
                UserVo userVo=BeanConvertUtils.convertBean(userMap.get(hktsOrder.getShipper()),UserVo.class);
                orderOnPCVo.setShipperName(userVo.getNickName());
            }catch (Exception e){
                log.error("订单列表货主Id{}用户数据异常",hktsOrder.getShipper());
            }

        }
        log.info("组装货主完成{}",DateUtils.intervalMillis(s,LocalDateTime.now()));
        orderOnPCVo.setCargo(hktsOrder.getCargoName());
        String weight=hktsOrder.getCargoWeight()+(hktsOrder.getCargoUnit()==null?"吨":hktsOrder.getCargoUnit());
        orderOnPCVo.setWeight(weight);

        return orderOnPCVo;

    }

    @Override
    public Result<HktsOrderDetailOnPCVo> getOrderDetailOnPc(String orderId) {
        HktsOrder hktsOrder=hktsOrderMapper.selectById(orderId);
        QueryWrapper<HktsContract> query = Wrappers.query();
        query.lambda().eq(HktsContract::getOrderId,orderId);
        HktsContract hktsContract=contractService.getOne(query);
        QueryWrapper<HktsOrderRecord> recordQueryWrapper=Wrappers.query();
        recordQueryWrapper.lambda().eq(HktsOrderRecord::getOrderId,orderId).orderByDesc(HktsOrderRecord::getCreateTime);
        List<HktsOrderRecord> record=recordMapper.selectList(recordQueryWrapper);
        log.info("pc查询订单详情数据：订单{}，合同{}，订单记录{}",hktsOrder,hktsContract,record);
        HktsOrderDetailOnPCVo hktsOrderDetailOnPCVo=BeanConvertUtils.copy(hktsOrder, HktsOrderDetailOnPCVo.class);
        hktsOrderDetailOnPCVo.setTransportPrice(hktsContract.getTransportPrice());
        hktsOrderDetailOnPCVo.setRecords(record);
        hktsOrderDetailOnPCVo.setCarrierPlate(hktsContract.getCarrierPlate());
        return ResultUtil.data(hktsOrderDetailOnPCVo);
    }

    @Override
    public Integer countOrder(String driver, Integer status) {
        QueryWrapper<HktsOrder> query = Wrappers.query();
        query.lambda().eq(!(driver == null || driver.isEmpty()),HktsOrder::getDriverId,driver)
                .eq(status!=null,HktsOrder::getOrderStatus,status);
        return hktsOrderMapper.selectCount(query);
    }

    @Override
    public List<UserOderNumVo> getOderNumByUserIds(String ids) {
        String[] split = ids.split(",");
        List<UserOderNumVo> list=  new ArrayList<UserOderNumVo>();
        //esClient
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //根据司机id进行分组计数
        TermsAggregationBuilder field =AggregationBuilders.terms("driverId").field("driverId");
        ValueCountAggregationBuilder countField = AggregationBuilders.count("count_name").field("driverId");
        field.subAggregation(countField);
        searchSourceBuilder.aggregation(field);
        //配置查询参数
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.matchQuery("orderStatus", "4"));
        for(int i=0;i<split.length;i++){
            UserOderNumVo vo=new UserOderNumVo();
            vo.setId(split[i]);
            list.add(vo);
            queryBuilder.should(QueryBuilders.termQuery("driverId",split[i]));
        }
        searchSourceBuilder.query(queryBuilder);
        SearchRequest searchRequest = new SearchRequest(CARGO_ORDER_INDEX);
        searchRequest.source(searchSourceBuilder);
        Map<String,Integer> map=new HashMap<>();
      try {
          SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);
          log.info(response.toString());
          ParsedStringTerms termsName = response.getAggregations().get("driverId");
          List<? extends Terms.Bucket> buckets = termsName.getBuckets();
          buckets.forEach(naem -> {
              String key = (String) naem.getKey();
              ParsedValueCount countName = naem.getAggregations().get("count_name");
              Double value = countName.value();
              map.put(key,value.intValue());
              log.info("driverId , count {} {}", key, value);
          });
          list.stream().forEach(userOderNumVo->{
              userOderNumVo.setOrderNum(map.get(userOderNumVo)==null?0:map.get(userOderNumVo));
          });
      }catch (Exception e){
          e.printStackTrace();
          log.info("查询es报错{}",e.getMessage());
      }
      //查询好评率

         List<UserOderNumVo> favorableRates=  driverCommentMapper.getfavorableRateByUserIds(split);
        Map<String, Float> collect1 = favorableRates.stream().collect(Collectors.toMap(UserOderNumVo::getId, UserOderNumVo::getFavorableRate));
        list.stream().forEach(userOderNumVo -> {
            userOderNumVo.setFavorableRate(collect1.get(userOderNumVo.getId()));
        });
        return list;
    }


     @Override
    public CustomPage<PayListVo> payPage(Page<PayListVo> page, PayParamtersVo vo) {
        QueryWrapper<HktsOrder> query = Wrappers.query();
        if (StringUtils.isNotBlank(vo.getDriverName())) {
            Result<List<String>> userByDriverName = frontInterface.getIdsByDriverName(vo.getDriverName());
            vo.setDriverIds(userByDriverName.getResult());
            query.lambda().in(HktsOrder::getDriverId, vo.getDriverIds());
        }
        if (StringUtils.isNotBlank(vo.getOwnerName())) {
            Result<List<UserBasicInfoVo>> userByNickName = feignInterface.getUserByNickName(vo.getOwnerName());
            List<UserBasicInfoVo> result = userByNickName.getResult();
            List<String> collect1 = result.stream().map(UserBasicInfoVo::getId).distinct().collect(Collectors.toList());
            vo.setShipperIds(collect1);
        }
        IPage<PayListVo> list = hktsOrderMapper.selectPayPage(page, vo);
        List<PayListVo> records = list.getRecords();
        if (records.size() > 0) {
            Set<String> collect = records.stream().map(PayListVo::getDriverId).collect(Collectors.toSet());
            Iterator it = collect.iterator();
            StringBuffer ids = new StringBuffer();
            while (it.hasNext()) {
                ids.append(it.next().toString()).append(",");
            }
            Result<Map<String, String>> driverNamesByIdsBy = frontInterface.getDriverNamesByIdsBy(ids.toString());
            for (int i = 0; i < records.size(); i++) {
                list.getRecords().get(i).setDriverName(driverNamesByIdsBy.getResult().get(records.get(i).getDriverId()));

            }
            //货主
            List<String> collectShipper = records.stream().map(PayListVo::getShipper).collect(Collectors.toList());
            Result<Map<String, Object>> usersByuserIds = feignInterface.getUsersByuserIds(collectShipper);
            for(int i=0;i<records.size();i++){
                UserVo userVo = BeanConvertUtils.convertBean(usersByuserIds.getResult().get(records.get(i).getShipper()), UserVo.class);
                list.getRecords().get(i).setShipperName(userVo.getNickName());
            }

            //查询货源单位
            List<String> unit = records.stream().map(PayListVo::getCargoId).collect(Collectors.toList());
            //cargoMapper
            QueryWrapper<HktsCargo> queryCargo = Wrappers.query();
            queryCargo.lambda().in(HktsCargo::getId, unit);
            List<HktsCargo> hktsCargos = cargoMapper.selectList(queryCargo);
            Map<String, String> collect1 = hktsCargos.stream().collect(Collectors.toMap(HktsCargo::getId, HktsCargo::getCargoUnit));
            String unitv = "";
            for (int i = 0; i < records.size(); i++) {
                unitv = collect1.get(list.getRecords().get(i).getCargoId()) == null ? "吨" : collect1.get(list.getRecords().get(i).getCargoId());
                list.getRecords().get(i).setCargoWeight(list.getRecords().get(i).getCargoWeight() + unitv);
            }
        }
        CustomPage customPage = CustomPageUtils.getCustomPage(list);
        return customPage;
    }
    @Override
    public Result<CustomPage> getDriverTradingOnPc(Page<OrderAndContract> page, String driverId) {
        QueryWrapper<HktsOrder> query = Wrappers.query();
        query.lambda().eq(HktsOrder::getDriverId,driverId)
        .eq(HktsOrder::getOrderStatus,OrderTypeEnum.DONE);
        IPage<OrderAndContract> page1=hktsOrderMapper.selectOrderAndContract(page,query);
        List<OrderAndContract> orderAndContracts=page1.getRecords();
        List<String> userIds = new ArrayList<>();
        List<String> driverIds = new ArrayList<>();
        for (OrderAndContract item:orderAndContracts
        ) {
            userIds.add(item.getShipper());
            driverIds.add(item.getDriverId());
        }
        Result<Map<String, Object>> user= feignInterface.getUsersByuserIds(userIds);
        Result<Map<String,Object>>  driver=frontInterface.getDriverInfosByUserIds(driverIds);
        List<HktsOrderOnPCVo> hktsOrderOnPCVos= orderAndContracts.stream().map(t->getHktsOrderOnPCVo(t,user,driver)).collect(Collectors.toList());
        CustomPage customPage= CustomPageUtils.getCustomPage(page1);
        customPage.setResultData(hktsOrderOnPCVos);
        return ResultUtil.data(customPage);
    }

    @Override
    public PayListVo getPayDetail(String orderId) {
        PayDetailInfoVo vo = hktsOrderMapper.getPayDetail(orderId);
        Result<UserVo> userByuserId = feignInterface.getUserByuserId(vo.getShipper());
        vo.setShipperName(userByuserId.getResult().getNickName());
        if(vo.getReceivingTime()!=null){
            vo.setTimeToBetPaid(vo.getReceivingTime().plusDays(vo.getPayTime()));
        }
        Result<UserAndRealNameVo> driverInfoByUserId = frontInterface.getDriverInfoByUserId(vo.getDriverId());
        if(driverInfoByUserId.getResult()!=null){
            vo.setDriverName(driverInfoByUserId.getResult().getDriverName());
        }
       if(StringUtils.isNotBlank(vo.getFreightPaymentUser())){
           Result<UserVo> freightPaymentUser = feignInterface.getUserByuserId(vo.getFreightPaymentUser());
           vo.setFreightPaymentUserName(freightPaymentUser.getResult().getNickName());
           vo.setFreightPaymentUser(freightPaymentUser.getResult().getNickName());
       }
        return vo;
    }
    @Override
    public void updatePayInfo(String orderId, String payId, float actualWeight,String actualTime) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        UpdatePayInfoParameterVo vo=new UpdatePayInfoParameterVo();

        vo.setActualWeight(actualWeight);
        vo.setFreightPaymentTime(LocalDateTime.now());
        vo.setOrderId(orderId);
        vo.setPayTransport(payId);
        vo.setActualPayTime(LocalDateTime.parse(actualTime,df));
        Result<UserBasicInfoVo> userBasicInfoVoResult = feignInterface.remoteUserBasicInfo();
        vo.setFreightPaymentUser(userBasicInfoVoResult.getResult().getId());
        hktsOrderMapper.updatePayInfo( vo);
    }
    @Override
    public int selectCount(String cargoId){
        QueryWrapper<HktsOrder> query = Wrappers.query();
        query.lambda().eq(HktsOrder::getCargoId,cargoId);
        return hktsOrderMapper.selectCount(query);
    }

    @Override
    public List<PayExportListVo> exportPayList(PayParamtersVo vo, HttpServletResponse response) throws IOException {
        QueryWrapper<HktsOrder> query = Wrappers.query();
        if (StringUtils.isNotBlank(vo.getDriverName())) {
            Result<List<String>> userByDriverName = frontInterface.getIdsByDriverName(vo.getDriverName());
            vo.setDriverIds(userByDriverName.getResult());
            query.lambda().in(HktsOrder::getDriverId, vo.getDriverIds());
        }
        if (StringUtils.isNotBlank(vo.getOwnerName())) {
            Result<List<UserBasicInfoVo>> userByNickName = feignInterface.getUserByNickName(vo.getOwnerName());
            List<UserBasicInfoVo> result = userByNickName.getResult();
            List<String> collect1 = result.stream().map(UserBasicInfoVo::getId).distinct().collect(Collectors.toList());
            vo.setShipperIds(collect1);
        }
        List<PayExportListVo> records = hktsOrderMapper.selectPayList(vo);



        if(records.size()>0){
            //司机名称
            Set<String> collect = records.stream().map(PayListVo::getDriverId).collect(Collectors.toSet());
            Iterator it = collect.iterator();
            StringBuffer ids=new StringBuffer();
            while (it.hasNext()) {
                ids.append(it.next().toString()).append(",");
            }
            Result<Map<String, String>> driverNamesByIdsBy = frontInterface.getDriverNamesByIdsBy(ids.toString());
            for(int i=0;i<records.size();i++){
                records.get(i).setDriverName(driverNamesByIdsBy.getResult().get(records.get(i).getDriverId()));
            }
            //货主
            List<String> collectShipper = records.stream().map(PayListVo::getShipper).collect(Collectors.toList());
            Result<Map<String, Object>> usersByuserIds = feignInterface.getUsersByuserIds(collectShipper);
            for(int i=0;i<records.size();i++){
                UserVo userVo = BeanConvertUtils.convertBean(usersByuserIds.getResult().get(records.get(i).getShipper()), UserVo.class);
                records.get(i).setShipperName(userVo.getNickName());
            }


            //查询货源单位
            List<String> unit = records.stream().map(PayListVo::getCargoId).collect(Collectors.toList());
            //cargoMapper
            QueryWrapper<HktsCargo> queryCargo = Wrappers.query();
            queryCargo.lambda().in(HktsCargo::getId,unit);
            List<HktsCargo> hktsCargos = cargoMapper.selectList(queryCargo);
            Map<String, String> collect1 = hktsCargos.stream().collect(Collectors.toMap(HktsCargo::getId, HktsCargo::getCargoUnit));
            Map<String, BigDecimal> collectPrice = hktsCargos.stream().collect(Collectors.toMap(HktsCargo::getId, HktsCargo::getTransportPrice));
            String unitv="";
            for(int i=0;i<records.size();i++){
                unitv=collect1.get(records.get(i).getCargoId())==null?"吨":collect1.get(records.get(i).getCargoId());
                records.get(i).setCargoWeight(records.get(i).getCargoWeight()+unitv);
                records.get(i).setTransportPrice(collectPrice.get(records.get(i).getCargoId()));
            }
        }
        exportPayData(records,response);
        return records;
    }
    public void exportPayData(List<PayExportListVo> records,HttpServletResponse response) throws IOException {
        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet sheet = wb.createSheet("支付列表");
        XSSFRow rowReportTitle = sheet.createRow(0);
        XSSFCell cell = rowReportTitle.createCell(0);
        cell.setCellValue("货主");
        XSSFCell cell1 = rowReportTitle.createCell(1);
        cell1.setCellValue("装货地-卸货地");
        XSSFCell cell2 = rowReportTitle.createCell(2);
        cell2.setCellValue("货物名称");
        XSSFCell cell3 = rowReportTitle.createCell(3);
        cell3.setCellValue("司机姓名");
        XSSFCell cell4 = rowReportTitle.createCell(4);
        cell4.setCellValue("车牌号");
        XSSFCell cell5= rowReportTitle.createCell(5);
        cell5.setCellValue("承运重量");
        XSSFCell cell6= rowReportTitle.createCell(6);
        cell6.setCellValue("运输单价");
        XSSFCell cell7= rowReportTitle.createCell(7);
        cell7.setCellValue("预估运费");
        XSSFCell cell8= rowReportTitle.createCell(8);
        cell8.setCellValue("收款人");
        XSSFCell cell9= rowReportTitle.createCell(9);
        cell9.setCellValue("银行卡号");
        XSSFCell cell10= rowReportTitle.createCell(10);
        cell10.setCellValue("开户行");
        XSSFCell cell11= rowReportTitle.createCell(11);
        cell11.setCellValue("确认收货时间");
        XSSFCell cell12= rowReportTitle.createCell(12);
        cell12.setCellValue("支付状态");
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        for(int i=0;i<records.size();i++){
            XSSFRow rowReportContent = sheet.createRow(i+1);
            XSSFCell cellOwenr = rowReportContent.createCell(0);
            cellOwenr.setCellValue("huozhu");
            XSSFCell cellAdress = rowReportContent.createCell(1);
            cellAdress.setCellValue(records.get(i).getAddress());
            XSSFCell cellCargoName = rowReportContent.createCell(2);
            cellCargoName.setCellValue(records.get(i).getCargoName());
            XSSFCell cellDriverName = rowReportContent.createCell(3);
            cellDriverName.setCellValue(records.get(i).getDriverName());
            XSSFCell cellCarCode = rowReportContent.createCell(4);
            cellCarCode.setCellValue(records.get(i).getCarrierPlate());
            XSSFCell cellWeight= rowReportContent.createCell(5);
            cellWeight.setCellValue(records.get(i).getCargoWeight());
            XSSFCell cellPrice= rowReportContent.createCell(6);
            cellPrice.setCellValue(records.get(i).getTransportPrice().floatValue());
            XSSFCell cellTotalPrice= rowReportContent.createCell(7);
            cellTotalPrice.setCellValue(records.get(i).getTotalTransportPrice().floatValue());
            XSSFCell cellPayee= rowReportContent.createCell(8);
            cellPayee.setCellValue(records.get(i).getPayee());
            XSSFCell cellBankCode= rowReportContent.createCell(9);
            cellBankCode.setCellValue(records.get(i).getBankCode());
            XSSFCell cellBank= rowReportContent.createCell(10);
            cellBank.setCellValue(records.get(i).getCollectingBank());
            XSSFCell cellRecivetime= rowReportContent.createCell(11);
            cellRecivetime.setCellValue(dtf2.format(records.get(i).getReceivingTime()));
            XSSFCell cell1PayStatus= rowReportContent.createCell(12);
            String payTransportStatus = records.get(i).getPayTransportStatus();
            if(payTransportStatus.equals("0")){
                cell1PayStatus.setCellValue("未支付");
            }else{
                cell1PayStatus.setCellValue("已支付");
            }
        }
        // 输出Excel文件
        OutputStream output = response.getOutputStream();
        response.reset();
        // 设置文件头
        response.setHeader("Content-Disposition",
                "attchement;filename=" + new String(("支付列表.xls").getBytes("gb2312"), "ISO8859-1"));
        response.setContentType("application/msexcel");
        wb.write(output);
        wb.close();
    }
}
